//
//  NetworkRequest.m
//  Leisure
//
//  Created by lanou on 16/4/19.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "NetworkRequest.h"

@implementation NetworkRequest

+ (void)getUrl:(NSString *)urlStr CallBack:(void (^)(id))callBack {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 返回主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            if (data) {
                callBack(data);
                /*
                // 通知
                [[NSNotificationCenter defaultCenter]postNotificationName:@"119" object:data];
                */
            } else {
                callBack(error);
            }
        });
        
    }];
    [task resume];
}

+ (void)postUrl:(NSString *)urlStr parameter:(NSDictionary *)dic callBack:(void (^)(id))callBack {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [NetworkRequest parameterToData:dic];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 返回主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            if (data) {
                callBack(data);
            } else {
                callBack(error);
            }
        });
    }];
    [task resume];
    
}

+ (NSData *)parameterToData:(NSDictionary *)dic {
    NSString *parameterStr = @"";
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *key in dic) {
        [arr addObject:[NSString stringWithFormat:@"%@=%@", key, dic[key]]];
    }
    parameterStr = [arr componentsJoinedByString:@"&"];
    NSData *data = [parameterStr dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

@end
